import json

def filter_backtracking_results(backtracking_results, delete_intervals, target_noid):

    for result in backtracking_results:
        noid = result["noid"]
        if noid != target_noid:
            continue
        outputs = result["result"]
        sims = result["sims"]

        # 标记需要删除的索引
        to_delete_indices = []

        for i, (output, sim) in enumerate(zip(outputs, sims)):
            start, end = output
            if [start, end] in delete_intervals:
                to_delete_indices.append(i)

        if to_delete_indices:
            # 检查是否有源节点被删除
            if any(sims[i] >= 1 for i in to_delete_indices):
                # 如果有源节点被删除，删除整个结果
                backtracking_results.remove(result)
                continue

            # 否则，只删除从节点
            result["result"] = [output for i, output in enumerate(outputs) if i not in to_delete_indices]
            result["sims"] = [sim for i, sim in enumerate(sims) if i not in to_delete_indices]

    return backtracking_results

if __name__ == "__main__":
    meta_path = "E:\\projects\\江苏数据\\201\\00-00-00-1-meta.json"
    # delete_ranges = [[37218, 37227]]
    delete_ranges = [[72895, 72904]]
    target_noid = '02a2c8ec-2650-40d7-afb4-9bf0cd28288e'
    with open(meta_path, 'r') as f:
        meta_data = json.load(f)

    backtracking_results = meta_data.get("backtracking_results", [])
    query_info = meta_data.get("query_info", [])

    # 创建 noid 映射
    backtracking_noids = {result["noid"]: result for result in backtracking_results}
    query_noids = {info["noid"]: info for info in query_info}

    # 处理 backtracking_results 和 query_info
    filtered_backtracking_results = []
    filtered_query_info = []

    for noid in set(backtracking_noids.keys()).intersection(query_noids.keys()):
        backtracking_result = backtracking_noids[noid]
        query_info_entry = query_noids[noid]

        if not backtracking_result["result"]:
            # 如果 backtracking_results 中的 noid 对应的 results 为空，删除两边的 noid 字典
            continue

        filtered_backtracking_results.append(backtracking_result)
        filtered_query_info.append(query_info_entry)

    # 更新 meta_path 中的 backtracking_results 和 query_info
    meta_data["backtracking_results"] = filtered_backtracking_results
    meta_data["query_info"] = filtered_query_info

    backtracking_results = meta_data.get("backtracking_results", [])
    backtracking_results = filter_backtracking_results(backtracking_results, delete_ranges, target_noid)
    meta_data["backtracking_results"] = backtracking_results
    print()
